<template>
<view :class="['wx_auth', { abs: type }]">
	<block v-if="!type">
		<!-- #ifdef MP-WEIXIN -->
		<view :class="['wrap', {'nopad': categroy || showPad}]">
			<button plain open-type="getUserInfo" @getuserinfo="getInfo" v-if="!userInfo">
				<view class="head">
					<image class="avatar" :src="avatar"></image>
					<view class="tz">点击显示微信头像</view>
				</view>
			</button>
			<view class="head" v-if="userInfo && !categroy">
				<image class="avatar" :src="avatar"></image>
				<block v-if="userInfo">
					<view class="name padding-top-xs">{{ userInfo.nickName }}(ID:{{ userInfo.id }})</view>
					<view class="level">
						<view class='name' v-for="(item, index) in userInfo.rank" :key="index">
							<image :src="item.images" class="img"></image>
							<text class="text">{{ item.name }}</text>
						</view>			
					</view>					
				</block>
			</view>
			<view class="top" v-if="userInfo && categroy">
				<view><image class="avatar" :src="avatar"></image></view>
				<view>
					<text class="name">{{ userInfo.nickName }}</text>
					<text class="id" v-if="showid">ID:{{ userInfo.id }}</text>
					<text class="id" v-else-if="!showid && show">推荐人: {{ expName }}</text>
				</view>
			</view>				
		</view>	
		<!-- #endif -->
		<!-- #ifndef MP-WEIXIN -->
		<view :class="['wrap', {'nopad': categroy || showPad}]">
			<view class="head" v-if="!categroy">
				<image class="avatar" :src="avatar"></image>
				<block v-if="userInfo">
					<view class="name padding-top-xs">{{ userInfo.nickName }}(ID:{{ userInfo.id }})</view>
					<view class="level">
						<view class='name' v-for="(item, index) in userInfo.rank" :key="index">
							<image :src="item.images" class="img"></image>
							<text class="text">{{ item.name }}</text>
						</view>			
					</view>					
				</block>
			</view>
			<view class="top" v-else>
				<view><image class="avatar" :src="avatar"></image></view>
				<view>
					<text class="name">{{ userInfo.nickName }}</text>
					<text class="id" v-if="showid">ID:{{ userInfo.id }}</text>
					<text class="id" v-else-if="!showid && show">推荐人: {{ expName }}</text>
				</view>
			</view>				
		</view>			
		<!-- #endif -->
	</block>
	<block v-else>
		<!-- #ifdef MP-WEIXIN -->
		<block v-if="!userInfo && CheckURL">
			<button class="auth" plain open-type="getUserInfo" @getuserinfo="getInfo"></button>			
		</block>		
		<block v-else>
			<view class="auth" @tap="utils.LinkTo(link)"></view>
		</block>
		<!-- #endif -->
		<!-- #ifndef MP-WEIXIN -->
		<view class="auth" @tap="utils.LinkTo(link)"></view>
		<!-- #endif -->
	</block>
</view>
</template>

<script>
	// 微信授权认证页面 && 用户中心头部页面
	import { mapGetters, mapActions } from 'vuex'
	// #ifdef MP-WEIXIN	
    import { getAuth, PersonalMsg } from '@/common/api/users'
	import { requestURL } from '@/common/utils/config'
	import { page as key } from '@/common/utils/permission'
	// #endif
	export default {
		props: {
			showid: {
				type: Number,
				default: 1 // 是否显示id, 1显示id, 0显示推荐人
			},
			type: {
				type: Number,
				default: 0 // 0: 用户头部信息，1: 文本信息
			},
			expName: String,
			categroy: {
				type: Number,
				default: 0 // 0: 用户头部样式一，1: 用户头部样式二
			},
			show: {
				type: Number,
				default: 1 // 是否显示推荐人， 1显示，0不显示
			},
			showPad: {
				type: Boolean,
				default: false
			},
			link: {
				type: Object,
				default: () => {}
			}
		},
		data () {
			return {
				// #ifdef MP-WEIXIN
				auth: {},
				u: {}				
				// #endif
			}
		},
		computed: {
			...mapGetters([
				'userInfo'
			]),
			// #ifdef MP-WEIXIN
			CheckURL () {
				if (this.link && this.link.link === true) {
					return true
				}
				return this.link ? this.link.link.indexOf('个人中心') !== -1 || key.includes(this.link.link) : false
			},			
			// #endif
			avatar () {
				if (this.userInfo && this.userInfo.avatarUrl) {
					return this.userInfo.avatarUrl
				} else {
					return '/static/profile.png'
				}
			}
		},
		methods: {
			// #ifdef MP-WEIXIN			
			...mapActions([
				'getPayPwd',
				'getAddress'
			]),
		     async getInfo (res) {
				 if (!this.userInfo) {
					if (res.detail.errMsg === 'getUserInfo:ok') {
						uni.showLoading({ mask: true, title: '授权中' })
						await this.getLogin(res)							
						await this.getUserSessionKey()						
						await this.getLoginInfo()					
						await this.getRank()
						await this.getAddress()
						uni.setStorageSync('userInfo', this.u)
						this.$store.commit('SET_USERINFO', this.u)
						uni.hideLoading()
						uni.showToast({
							title: '授权成功'
						})
					} else {
						console.log(res.detail.errMsg)
					}					 
				 }
			},
			getLogin (res) {
				return new Promise(resolve => {
					uni.login({
						provider: 'weixin',
						success: data => {
							this.auth = res.detail.userInfo
							this.auth.iv = res.detail.iv
							this.auth.encryptedData = res.detail.encryptedData
							this.auth.signature = res.detail.signature
							this.auth.code = data.code
							this.auth.parent_id = ''
							this.auth.appid = this.$appid
							resolve()
						}
					})
				})
			},
			getUserSessionKey: function() {
				return new Promise((resolve, reject) => {
					uni.request({
						url: requestURL + '/api/Login/getsessionkey',
						method: 'post',
						data: this.auth,
						dataType: 'json',
						header: {
							'Content-Type': 'application/x-www-form-urlencoded'
						},
						success: res => {
							const data = res.data
							if (data.code === 0) {
								uni.showToast({ mask: true, icon: 'none', title: '授权失败,请重试' })
								reject('请重试')
							} else if (data.status === 0) {
								uni.showToast({
									icon: 'none', duration: 4000, title: '授权失败,请重试'
								})
							} else {
								this.auth.sessionId = data.session_key
								this.auth.openid = data.openid
								this.auth.unionid = data.unionid
								resolve()								
							}
						},
						fail: err =>{
							uni.showToast({
								icon: 'none',
								title: '授权失败,请重试'
							})
							uni.hideLoading()
							reject(err)
						}
					})
				})
			},
			getLoginInfo () {
				return new Promise((resolve) => {
					getAuth(this.auth).then(res => {
						this.u.avatarUrl = res.weixin_headimgurl
						this.u.id = res.id
						this.u.nickName = res.weixin_name
						this.u.pay_pwd = 0
						this.u.phone = res.account_phone
						this.u.rank = []
						this.u.ticket = res.ticket
						this.u.openid = res.openid
						this.u.uname = res.weixin_unionid
						uni.setStorageSync('userInfo', this.u)
				        this.getPayPwd().then(pw => {
							this.u.pay_pwd = pw
						     resolve()
						})						
					})					
				})
			},
			getRank () {
				return new Promise(resolve => {
					PersonalMsg().then(res => {
						this.u.rank = res.data
						resolve()
					})
				})
			}			
			// #endif
		}
	}
</script>

<style lang="less">
@import '../common/styles/variables.less';
.wx_auth {
	&.abs {
		position: absolute;
		top: 0;
		left : 0;
		width: 100%;
		height: 100%;
		z-index: 444;
	}
	button {
	 border-radius: 0;
	 padding: 0;
	 margin: 0;
	 appearance: none;
	 border: 0 none;
	 font-size:inherit;		
	}
	.auth {
		position: absolute;
		top: 0;
		left: 0;
		width: 100%;
		height: 100%;
	}
	.avatar {
		width: 150upx;
		height: 150upx;
		border-radius: 50%;
		overflow:hidden;
	}	
	.wrap {
		 background-color: @sliver;
		 overflow:hidden;
		 padding-bottom: 20upx;
		 &.nopad { padding-bottom: 0 }
		 .head {
			background-color:@headBg;
			color:white;
			display: flex;
			justify-content: center;
			align-items: center;
			flex-direction: column;
			flex-flow: column;
			padding: 40upx 0;
			position:relative;
			.name { 
				margin: 5upx 0 10upx;
			}
			.level {
				display: flex;
				justify-content: center;		
				.name {
					display: flex;
					align-items: center;
					justify-content: center;
					margin-right:12upx;
					position: relative;
					padding-right: 20upx;
					&:not(:last-of-type) {
						&::after {
							position: absolute;
							top: 0;
							right: 0;
							border-right:1px solid white;
							transform: scale(.5);
							content: '';
							height: 100%;
						}				
					}
					&:first-of-type {
						.img {
							padding-left: 0;
						}
					}
					&:last-of-type { margin-right: 0; }
					.img {
						width: 30upx;
						height: 30upx;
						vertical-align: middle;
					}
					.text {
						margin-left: 15upx;
						font-size: @minSize;
					}				
				}	
			}
		 }
		.top {
			background-color: @headBg;
			color: white;
			display: flex;
			padding: 40upx 15px;
			&>view {
				&:first-of-type {
					width: 150upx;
					margin-right: 20upx;
					display: flex;
					align-items: center;
					&>view {
						background-repeat: no-repeat;
						background-size: cover;
						background-position: top center;
						padding-top: 100%;
						border-radius: 50%;
					}
				}

				&:last-of-type {
					display: flex;
					flex-flow: column;
					flex-direction: column;
					justify-content: space-between;
					padding: 10upx 0;

					&>text {
						&.name {
							font-size: @title;
						}

						&.id {
							background: white;
							border-radius: 15upx;
							color: rgb(196,144,192);
							font-size: @minSize;
							padding: 5upx 20upx;
						}
					}
				}
			}
		}
		.tz {
			color:white;
			font-weight: 600;
			font-size:@title;
		}
	}	
}
</style>
